package role

import (
	"context"
	"database/sql"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"

	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type InfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRoleInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InfoLogic {
	return &InfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *InfoLogic) RoleInfo(in *pb.RoleInfoDetailReq) (*pb.RoleInfoDetailResp, error) {
	// 1.builder bo  ...
	roleBO := bo.SysRoleBO{
		RoleId: in.RoleId,
	}
	// 2.query in db ...
	roleEntity, err := mapper.NewRoleMapper().SelectOne(l.svcCtx.DBEngin, roleBO)
	if err != nil {
		logx.Errorf("select RoleInfo failed:%s", err.Error())
		return nil, err
	}
	if roleEntity.RoleId <= 0 {
		return nil, excption.NewErrCode(constans.RoleNoExistError)
	}
	// 3.query dept info
	deptBO := bo.SysDeptBO{
		DeptId: roleEntity.DeptId,
	}
	deptEntity, err := mapper.NewDeptMapper().SelectOne(l.svcCtx.DBEngin, deptBO)
	if err != nil {
		logx.Errorf("select deptEntity failed:%s", err.Error())
		return nil, err
	}
	if roleEntity.RoleId <= 0 {
		return nil, excption.NewErrCode(constans.DeptNoExistError)
	}
	// 4. query data permission
	selectList, err := mapper.NewRoleDeptMapper().SelectList(l.svcCtx.DBEngin,
		bo.SysRoleDeptBO{RoleId: sql.NullInt64{Int64: roleEntity.RoleId, Valid: true}})
	if err != nil {
		return nil, err
	}
	var deptIdArr []int64
	if len(selectList) > 0 {
		for _, v := range selectList {
			deptIdArr = append(deptIdArr, v.DeptId)
		}
	}
	// 5. query role menu List
	roleMenuArr, err := mapper.NewRoleMenuMapper().SelectList(l.svcCtx.DBEngin,
		bo.SysRoleMenuBO{RoleId: sql.NullInt64{Int64: roleEntity.RoleId, Valid: true}})
	if err != nil {
		return nil, err
	}
	var menuIdArr []int64
	if len(roleMenuArr) > 0 {
		for _, v := range roleMenuArr {
			menuIdArr = append(menuIdArr, v.MenuId.Int64)
		}
	}
	// 6.return obj ..
	return &pb.RoleInfoDetailResp{
		RoleId:     roleEntity.RoleId,
		RoleName:   roleEntity.RoleName,
		Remark:     roleEntity.Remark,
		CreateTime: roleEntity.CreateTime.Format("2006-01-02 15:04:05"),
		DeptId:     deptEntity.DeptId,
		DeptName:   deptEntity.Name,
		DeptIdArr:  deptIdArr,
		MenuIdArr:  menuIdArr,
	}, nil
}
